#include "oj_model2.hpp"
// #include "oj_model.hpp"
#include "oj_view.hpp"

#include "../comm/httplib.h"
#include "oj_control.hpp"

#include "login.hpp"
#include "register.hpp"

#include <signal.h>

using namespace httplib;
using namespace ns_control;


Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    //捕捉三号信号
    signal(SIGQUIT,Recovery);

    Server srv;
    Control ctrl;
    ctrl_ptr = &ctrl;
    
    //获取题目列表
    srv.Get("/all_questions",[&ctrl](const Request &req,Response &resp){
        std::string html;
        //获取所有题目列表的网页
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html;charset=utf-8");

        // resp.set_content("这是所有的题目列表","text/plain;charset=utf-8");
    });

    //获取指定题目
    //(\d+) 正则表达式,+d代表数字字符，+代表匹配前面的字符1次或多次
    //R"()" 原始字符串raw string,保持字符串内容的原貌，不用做相关的转义
    srv.Get(R"(/question/(\d+))",[&ctrl](const Request &req,Response &resp){
        std::string number = req.matches[1];
        std::string html;
        ctrl.OneQuestion(number,&html);
        resp.set_content(html,"text/html;charset=utf-8");

        // resp.set_content("这是编号为 "+number+" 号的题目","text/plain;charset=utf-8");
    });

    //提交代码
    srv.Post(R"(/judge/(\d+))",[&ctrl](const Request &req,Response &resp){
        std::string number = req.matches[1];
        std::string out_json;
        ctrl.Judge(number,req.body,&out_json);
        resp.set_content(out_json,"application/json;charset=utf-8");

        // resp.set_content("判题编号 "+number,"text/plain;charset=utf-8");
    });

    //注册
    srv.Post("/register",[](const Request &req,Response &resp){
        handle_register(req,resp);
    });

    //登录
    srv.Post("/login",[](const Request &req,Response &resp){
        handle_login(req,resp);
    });

    //设置web根目录
    srv.set_base_dir("./wwwroot");
    
    //启动服务器
    srv.listen("0.0.0.0",8080);
    return 0;
}